package io.lkt.common.utils;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @version : V1.0
 * @ClassName: NamedThreadFactory
 * @Description: 核心线程满了，则进入队列，队列满了，则创建新线程，当线程数达到最大线程数，则进入拒绝策略
 * @Auther: chujiu
 * @Date: 2021/3/7
 */

public class NamedThreadFactory implements ThreadFactory {

    private final AtomicInteger poolNumber = new AtomicInteger(1);

    private final ThreadGroup threadGroup;

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    public final String namePrefix;

    NamedThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        if (null == name || "".equals(name.trim())) {
            name = "pool";
        }
        namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }

    public static void main(String[] args) {
        // 核心线程满了，则进入队列，队列满了，则创建新线程，当线程数达到最大线程数，则进入拒绝策略
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 5, 1,
                TimeUnit.MINUTES, new LinkedBlockingDeque<>(), new NamedThreadFactory("测试"));
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 5; i++) {

            final int index = i;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread() + ":" + index);
                }
            });
        }
        threadPoolExecutor.shutdown();

        long time = System.currentTimeMillis() - beginTime;

        System.out.println("main thread is running" + time);
        System.out.println("===============结束================");

        // 轮询线程池的任务是否都执行完
        while (true){
            if(threadPoolExecutor.isTerminated()){
                long time2 = System.currentTimeMillis() - beginTime;
                System.out.println("多线程-thread is running-" + time2);
                System.out.println("===============多线程-结束================");
                break;
            }
        }
    }

}
